package com.zzyl.nursing.service.impl;


import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备管理Service业务层处理
 *
 * @author alexis
 * @date 2025-01-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private Client client;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }


    @Override
    public void syncProductList() {
        //向物联网平台查询设备信息
        QueryProductListRequest request = new QueryProductListRequest();
        request.setPageSize(100);
        request.setCurrentPage(1);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryProductListResponse response;
        //判断是否查询成功

        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!response.getBody().getSuccess()) {
            throw new BaseException("设备列表获取失败");
        }
        //获取查询的数据
        List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo = response.getBody().getData().getList().getProductInfo();
        //将数据存储到redis中
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, JSON.toJSONString(productInfo));


    }

    @Override
    public List<ProductVo> allProduct() {
        //从redis中获取数据
        String product = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        if (ObjectUtils.isEmpty(product)) {
            return Collections.emptyList();
        }
        List<ProductVo> list = JSONUtil.toList(product, ProductVo.class);
        return list;
    }

    @Override
    public void register(DeviceDto deviceDto) {
        //1.判断设备名称是否重复
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));

        //2.如果查到了就抛出异常
        if (count > 0) {
            throw new BaseException("设备名已存在，请从新输入");
        }
        //3.不存在则查询产品信息，将信息保存到IOT平台中
        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse response;
        try {
            response = client.registerDevice(registerDeviceRequest);
        } catch (Exception e) {
            throw new BaseException("调用物联网接口失败");
        }
        // 判断保存设备到iot平台是否成功
        if (!response.getBody().success) {
            throw new RuntimeException(response.getBody().getErrorMessage());
        }
        //4判断产品类型，设备是老人是就设置设备物理位置为—1
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }
        //拷贝数据
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //5.将返回的iotId写回对象中
        device.setIotId(response.getBody().getData().iotId);

        //6.将数据保存到数据库中
        try {
            int i = deviceMapper.insertDevice(device);
            if (i == 0) {
                deleteDevice(deviceDto);
                throw new BaseException("设备信息保存失败");
            }
        } catch (Exception e) {
            deleteDevice(deviceDto);
            throw new BaseException("该老人/位置已绑定该产品");
        }

    }

    //删除平台的设备信息
    public void deleteDevice(DeviceDto deviceDto) {

        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.setDeviceName(deviceDto.getDeviceName());
        deleteDeviceRequest.setProductKey(deviceDto.getProductKey());
        deleteDeviceRequest.setIotId(deviceDto.getIotId());
        deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        try {
            client.deleteDevice(deleteDeviceRequest);
        } catch (Exception e) {
            throw new BaseException("调用物联网接口失败");
        }

    }

    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        //从iot平台中获取数据
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setIotId(deviceDto.getIotId());
        request.setProductKey(deviceDto.getProductKey());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new BaseException("物联网联通失败");
        }
        if (!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }
        //将获取的数据拷贝的deviceVo中
        DeviceVo deviceVo = BeanUtil.toBean(response.getBody().getData(), DeviceVo.class);
        //查询数据库
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceVo.getIotId()));
        //将从数据库总查询到的数据拷贝到DeviceVo中
        BeanUtil.copyProperties(device, deviceVo);


        return deviceVo;
    }

    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("调用物联网接口失败");
        }
        if (!response.getBody().success) {
            throw new BaseException(response.getBody().errorMessage);
        }

        return AjaxResult.success(response.getBody().data);
    }

    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("调用物联网接口失败");
        }
        if (!response.getBody().getSuccess()) {
            throw new BaseException(response.getBody().getErrorMessage());
        }
        return AjaxResult.success(response.getBody().getData());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDevice(Device device) {
        //修改数据库信息
        try {
            int i = deviceMapper.updateDevice(device);
        } catch (Exception e) {
            throw new BaseException("更新数据库失败");
        }
        //修改iot平台上的昵称
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> nicknameInfos =new ArrayList<>();
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo nicknameInfo =new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        nicknameInfo.setDeviceName(device.getDeviceName());
        nicknameInfo.setNickname(device.getNickname());
        nicknameInfo.setProductKey(device.getProductKey());
        nicknameInfos.add(nicknameInfo);
        request.setDeviceNicknameInfo(nicknameInfos);

        BatchUpdateDeviceNicknameResponse response;
        try {
             response = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new BaseException("调用物联网接口失败");
        }
        if(!response.getBody().getSuccess()){
            throw new BaseException(response.getBody().getErrorMessage());
        }


    }
}
